from dytz.backtest import *
from dytz.params import *
from dytz.data import *
from dytz.context import *
from dytz.bar import *

import numpy as np

class DNGNode1(DNGNode):
    __params__ = {
        'k': Param(int, min_val=10, max_val=41, step=2),
        'n1': Param(int, min_val=60, max_val=91, step=2),
        'n2': Param(int, min_val=5, max_val=46, step=2),
        't': Param(float, min_val=0.01, max_val=0.03, step=0.002)
    }

    def init_node(self):
        n = self.params['k']
        self.H = TimeSeries(n)
        self.L = TimeSeries(n)
        self.C = TimeSeries(n)
        self.O = TimeSeries(n)
        self.wl = TimeSeries(n)

    def on_bar(self, ctx: Context, bar: Bar):
        n1 = self.params['n1']
        n2 = self.params['n2']
        self.H.step()
        self.L.step()
        self.C.step()
        self.O.step()
        self.H.set(bar.HIGH)
        self.L.set(bar.LOW)
        self.C.set(bar.CLOSE)
        self.O.set(bar.OPEN)
        self.wl.step()

        a = (self.H.timearray.max() - bar.CLOSE) / (self.H.timearray.max() - self.L.timearray.min()) * 100
        self.wl.set(a)
        if self.wl[0] >= n1 and bar.CLOSE > self.C[1]:
            if ctx.pos == 0:
                ctx.open_long(bar.AVGPRICE)

        if self.wl[0] <= n2 and bar.CLOSE < self.C[1]:
            if ctx.pos == 0:
                ctx.open_short(bar.AVGPRICE)

        t = self.params['t']
        pos = ctx.pos
        if pos > 0 and ctx.max_low is not None:
            if bar.CLOSE < ctx.max_low * (1 - t):
                ctx.cover_long(bar.AVGPRICE)
        elif pos < 0 and ctx.min_high is not None:
            if bar.CLOSE > ctx.min_high * (1 + t):
                ctx.cover_short(bar.AVGPRICE)
        # ctx.open_long(price=bar.AVGPRICE)

model = [DNGNode1(k=28, n1=73, n2=16, t=0.014)]

#
# rolling_back(model, '000905.SH', '20100101', '20221021', file_name='roll')
# select_params(model, '000905.SH', '20100101', '20221021')
# rolling_back2(model, '000905.SH', '20100101', '20221021')

if __name__ == '__main__':
    # select_params2(model, '000905', '20100101', '20221021')
    # backtest(model, '000905.SH', '20100101', '20221021', plot=True, res_type='score', file_name='dhsd.xlsx')
    # select_params(model, '000905.SH', '20100101', '20221021')
    # rolling_back2(model, '000905.SH', '20100101', '20221021')
    summarization_data(model, '000905', '20100101', '20221021', sel_type='ga')